<?php
namespace php\widgets\editorxml;
use Yii;
use yii\helpers\Html;
class EditorWidget extends \yii\base\Widget{
	public $id;
	public $type;
	public $lang;
	public $data;

	private $_widgets = [
		'layout' => WebLayoutWidget::class,
		'editor' => WebEditorWidget::class,
		'images' => WebImagesWidget::class,
		'image' => WebImageWidget::class,
		'text' => WebTextWidget::class,
		'textH1' => WebTextH1Widget::class,
		'slider' => WebSliderWidget::class,
		'homeSlider' => WebHomeSliderWidget::class,
		'collapse' => WebCollapseWidget::class,
		'listContainer' => WebListContainerWidget::class,
		'container' => WebContainerWidget::class,
		'tabs' => WebTabsWidget::class,
	];

	public function run(){
		$widgets = null;
		switch ($this->type) {
			case 'release':
				$xmlObject = simplexml_load_string($this->data);
				$json = json_encode($xmlObject);
				$widgets = json_decode($json, true);
			break;
			
			default:
				$widgets = Yii::$app->pageService->getPreview($this->id, $this->lang);
			break;
		}
		$shtml = '';
		if(!empty($widgets)){
			foreach ($widgets as $key => $val) {			
				$inner = $this->renderNode($key, $val);
				$shtml .= Html::tag('section', $inner);
			}
		}

		return $shtml;
	}

	public function renderNode($type, $val, $parent_type = '', $counter=0){
		if($counter >10) return null;
		$attributes = isset($val['@attributes']) ? $val['@attributes'] : null;
		if(!empty($attributes)){
			$widget_id = $attributes['id'];
			$widget_data = json_decode($attributes['data'], true);
		}
		unset($val['@attributes']);
		$child_html = '';
		if(!empty($val)){
			foreach($val as $node_type => $child_node){
				$child_html .= $this->renderNode($node_type, $child_node, $type, $counter++);
			}
		}
		return $this->renderWidget($type, isset($widget_data) ? $widget_data : null, $parent_type, $child_html);
	}
	public function renderWidget($type, $val, $parent_node='',$child_html=''){
		if(isset($this->_widgets[$type])){
			$widgetClass = $this->_widgets[$type];
			$shtml = $widgetClass::widget([
				'value'=> $val, 
				'child'=> $child_html,
				'that' => $this,
				'parent_type' => $parent_node,
			]);
			return $shtml;
		}	
		return null;
	}
}